package com.bigdata.datamock.jdbc;

import com.bigdata.datamock.util.HikaricpUtils;
import com.github.javafaker.Faker;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;

import java.sql.*;
import java.util.Locale;
import java.util.UUID;

/**
 * @BelongsProject: realtime-project-10zlq
 * @BelongsPackage: com.bigdata.datamock.jdbc
 * @Author: zhangleqing
 * @CreateTime: 2025-08-20  22:06
 * @Description: TODO
 * @Version: 1.0
 */
public class CarsLogJDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://node101:3306/sca?rewriteBatchedStatements=true&characterEncoding=utf8";
        String user = "root";
        String password = "123456";
        Connection conn = null;
        PreparedStatement pstm =null;
        ResultSet rt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            String qsql = "SELECT c.carCode ,h.cid from sca.cars c left join sca.ower o on c.owerId = o.id left join sca.room r on o.roomId = r.id left join sca.house h on r.houseId = h.id where c.id=?";
            String sql = "INSERT INTO cars_Log(id,opTime,ctype,carCode,cId) VALUES(?,?,?,?,?)";
            pstm = conn.prepareStatement(sql);
            Long startTime = System.currentTimeMillis();
            Faker fakerZH = new Faker(new Locale("zh-CN"));
            QueryRunner qr =  new QueryRunner(HikaricpUtils.getDataSource());
            Object[] objArr = null;
            for (int i = 1; i <= 100; i++) {
                Thread.sleep(1000);
                objArr = qr.query(qsql,new ArrayHandler(),fakerZH.number().numberBetween(10000000,10096005));
                pstm.setString(1, UUID.randomUUID().toString());
                pstm.setString(2, new Timestamp(System.currentTimeMillis())+"");
                pstm.setInt(3, fakerZH.number().numberBetween(1,3));
                pstm.setString(4, objArr[0].toString());
                pstm.setInt(5,Integer.parseInt(objArr[1]+""));
                pstm.execute();
                //pstm.addBatch();
            }
            //pstm.executeBatch();
            Long endTime = System.currentTimeMillis();
            System.out.println("OK,用时：" + (endTime - startTime));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
